var first_try = function() {
    $('body').append('<div id=fd>Hello world</div>');
    $('#fd').css('width', '500px');
    $('#fd').css('height', '400px');
    $('#fd').css('background-image', 'url("http://wilderness150.files.wordp\
ress.com/2010/03/mount-rainier.jpg")');
};


var aspectRatio = 1000;
/**
 * Packages the parameters into a delta object for use with submitDelta.
 * @param {!(string|Object.<!string, !string>)}  Either an object denoting
 *     the desired key value pair(s), or a single string key.
 * @param {!string=} opt_value If keyOrState is a string, the associated
 *     string value.
 */
var prepareForSave = function(keyOrState, opt_value) {
  var state = null;
  if (typeof keyOrState === 'string') {
    state = {};
    state[keyOrState] = opt_value;
  } else if (typeof keyOrState === 'object' && null !== keyOrState) {
    // Ensure that no prototype-level properties are hitching a ride.
    state = {};
    for (var key in keyOrState) {
      if (keyOrState.hasOwnProperty(key)) {
        state[key] = keyOrState[key];
      }
    }
  } else {
    throw 'Unexpected argument.';
  }
  return state;
};

var image_url;

/* Steps when initiated the app:
 * 1, construct the static content of the app
 * 2, possiblly prepare audio/image resources (not in the app)
 * 3, set up the handlers on state/participants changes
 * 4, getting the state/paticipants from the shared state
 * 5, render the dynamical content of the app based on state/paticipants.
 */
var appInit = function() {
  // Div for holding the whold cavnas
    $('body').append('<div id="outter"></div>'); 
    // Div to wrap the background image 
    $('body').append('<div id="bgdiv"></div>'); 
    
    // Div for the forms
    $('#outter').append('<div id=img-picker class="picker subcap"></div>');
    var imgInput = $('<form id="img-picker-form" action="" >');
    imgInput.append('image url:').append('<input type="text" id="image_url" />');
    imgInput.append($('<input type="submit" value="Set" id="change_url"/>'));
    imgInput.append($('<input type="submit" value="Clear Url" id="clear_url"/>'));
    $('#img-picker').append(imgInput);

    // bind the sumbit handler
    // $('#img-picker-form').submit(function() {
    //     var url = $('#image_url').val();
    //     console.log(url);
    //     //save the url to the shared state
    //     var newState = prepareForSave('shared-image', url);
    //     gapi.hangout.data.submitDelta(newState, null);
    //     return false;
    //  });

     $('#change_url').click(function() {
        var url = $('#image_url').val();
        console.log(url);
        //save the url to the shared state
        var newState = prepareForSave('shared-image', url);
        gapi.hangout.data.submitDelta(newState, null);
        return false;
      });

     $('#clear_url').click(function() {
        console.log("clearn image url");
        $('#image_url').val('');
        return false;
      });

    // Set up state change listener
     gapi.hangout.data.onStateChanged.add(function(stateChangeEvent) {
          updateLocalDataStateAndRender(stateChangeEvent.state,
                               stateChangeEvent.metadata);
        });

    // Getting the image url from the shared state
    // TODO: Consider using a object like state to hold all information
    // about the app.
    if (!image_url) {
      var state = gapi.hangout.data.getState();
      var metadata = gapi.hangout.data.getStateMetadata();
      if (state && metadata) {
        updateLocalDataState(state, metadata);
      }
    }

    // render
    render();

    //$('body').append('<div id="bg"><img src="http://wilderness150.files.wordpress.com/2010/03/mount-rainier.jpg" class="bg"></div>');
    //var later = setTimeout("render()", 3000);
};

var updateLocalDataState = function(state, metadata){
  image_url = state['shared-image'];
};

var updateLocalDataStateAndRender = function(state, metadata){
  image_url = state['shared-image'];
  render();
}

/* Render the app based on the dynamical information
 * which can be changed by the shared states or on
 * user interactons in the page
 */
var render = function() {
  //change the background image
  if(!image_url) {
    console.log('no image_ulr');
    return;
  }
  $('#bgdiv').empty().append('<img src="' + image_url + '" id="bg">');

  //resizeImage();
};

// register start point
gapi.hangout.onApiReady.add(appInit);


//////////////////// TODO: How to get width/height of iframe? ///////
var resizeImage = function() {
  var theWindow        = $('#outter');
  console.log(theWindow.width());
  console.log(theWindow.height());
  $bg              = $("#bg");
  aspectRatio = 1000;
  if ($bg.size() > 0) {
    aspectRatio      = $bg.width() / $bg.height();
  }
  // tried to use $('#outter').width, but it doesn't
  // include the size of the image.
  // it will be nice if I can get the width and height of the iframe?
  // however, $('#iframe', parent.document)[0] will cause an security warning.
  // howwwwww?
  if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
    //if (637.0/438.0  < aspectRatio ) { 
    $bg  
    .removeClass()
    .addClass('bgheight');
  } else {
    $bg
    .removeClass()
    .addClass('bgwidth');
  }
};